﻿using System.Collections.Generic;
using System.Linq;
using DataBaseLayer.Abstractions;
using DataBaseLayer.Abstractions.Interfaces.Services;
using DataBaseLayer.Dto;
using DataBaseLayer.Extensions;

namespace DataBaseLayer.Services
{
	public class BusinessTripOrdersService : BaseService, IOrdersService<BusinessTripOrderData>
	{
		#region Constructors

		public BusinessTripOrdersService(DocumentManager dataBase)
			: base(dataBase) { }

		#endregion

		#region IOrdersService Members

		public IEnumerable<BusinessTripOrderData> GetOrders()
		{
			return DataBase.BusinessTripOrders.ToDtos();
		}

		public BusinessTripOrderData GetOrderById(int id)
		{
			return DataBase.BusinessTripOrders.SingleOrDefault(lo => lo.Id == id).ToDto();
		}

		public void CreateOrder(BusinessTripOrderData orderData, LogOrderData logOrderData)
		{
			if (orderData == null || logOrderData == null) return;

			var entity = new BusinessTripOrder
			{
				AuthorSignature = orderData.AuthorSignature,
				Date = orderData.Date,
				Number = orderData.Number,
				Person = orderData.Person,
				Profession = orderData.Profession,
				StartDate = orderData.StartDate,
				Cause = orderData.Cause,
				City = orderData.City,
				EndDate = orderData.EndDate,
				LogOrder = new LogOrder
				{
					Date = logOrderData.Date,
					Description = logOrderData.Description,
					Number = logOrderData.Number,
					Performer = logOrderData.Performer
				}
			};
			DataBase.BusinessTripOrders.Add(entity);
			DataBase.SaveChanges();
		}

		public void UpdateOrder(BusinessTripOrderData orderData, LogOrderData logOrderData)
		{
			if (orderData == null || logOrderData == null) return;

			var oldEntity = DataBase.BusinessTripOrders.SingleOrDefault(lo => lo.Id == orderData.Id);
			if (oldEntity == null) return;

			oldEntity.AuthorSignature = orderData.AuthorSignature;
			oldEntity.Date = orderData.Date;
			oldEntity.Number = orderData.Number;
			oldEntity.Person = orderData.Person;
			oldEntity.Profession = orderData.Profession;
			oldEntity.StartDate = orderData.StartDate;
			oldEntity.Cause = orderData.Cause;
			oldEntity.City = orderData.City;
			oldEntity.EndDate = orderData.EndDate;

			oldEntity.LogOrder.Date = logOrderData.Date;
			oldEntity.LogOrder.Description = logOrderData.Description;
			oldEntity.LogOrder.Number = logOrderData.Number;
			oldEntity.LogOrder.Performer = logOrderData.Performer;

			DataBase.SaveChanges();
		}

		public void DeleteOrderById(int id)
		{
			var delOrder = DataBase.BusinessTripOrders.SingleOrDefault(lo => lo.Id == id);
			if (delOrder == null) return;
			DataBase.BusinessTripOrders.Remove(delOrder);
			DataBase.SaveChanges();
		}

		#endregion
	}
}
